package com.AAA.controllor;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.UUID;

@RestController
public class fileController {

    @PostMapping("upfile")
    public String upfile(MultipartFile file, HttpServletRequest request){
        /*获取文件的名称*/
        String filename=file.getOriginalFilename();
        System.out.println("file="+file.getOriginalFilename());
        /*获取当前项目路径*/
        String realPath=request.getServletContext().getRealPath("/upload");
        System.out.println(realPath);
        File file1=new File(realPath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        UUID uuid = UUID.randomUUID();
        int i = filename.lastIndexOf(".");
        String substring = filename.substring(i);
        String newname=uuid+substring;
        try {
            OutputStream outputStream=new FileOutputStream(file1+File.separator+newname);

            InputStream inputStream = file.getInputStream();

            int len=0;
            while((len=inputStream.read())!=-1){
                outputStream.write(len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            // 路径保存到数据库即可
            String picpath=realPath+File.separator+newname;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "index";
    }

    @PostMapping("upfile2")
    public String upfile2(MultipartFile file, HttpServletRequest request){
        /*获取文件的名称*/
        String filename=file.getOriginalFilename();
        System.out.println("file="+file.getOriginalFilename());
        /*获取当前项目路径*/
        String realPath=request.getServletContext().getRealPath("/upload");
        System.out.println(realPath);
        File file1=new File(realPath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        UUID uuid = UUID.randomUUID();
        int i = filename.lastIndexOf(".");
        String substring = filename.substring(i);
        String newname=uuid+substring;

        File file2 = new File(realPath+File.separator+newname);
        try {
            file.transferTo(file2);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String picpath=realPath+File.separator+newname;

        return "index";
    }

    @PostMapping("upfile3")
    public String uploadFile3(MultipartFile file, HttpServletRequest request){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // oss-cn-beijing.aliyuncs.com
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tQ7h8HkuniQr2JEPrai";
        String accessKeySecret = "dAhFfzng93jLW3mrZg9GdLoI7KDjra";
        // 填写Bucket名称，例如examplebucket。
        String filename=file.getOriginalFilename();
        String bucketName = "liangmenglei";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。

        // 新的名字
        String s = UUID.randomUUID().toString();// DJKAHGFJSHGHKFSHKJDFG
        // 无标题.png  1.3.4.5.jpg
        // +.JPG  PNG JEPG
        // 获取原来的文件的后缀 oldname
        String oldname=file.getOriginalFilename();
        int i = oldname.lastIndexOf(".");
        String suffixname = oldname.substring(i);
        //System.out.println("suffixname = " + suffixname);
        String newname=s+suffixname;
        //System.out.println("newname = " + newname);


        String objectName = newname;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 填写字符串。
            String content = "Hello OSS";

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传字符串。
            ossClient.putObject(putObjectRequest);
            String picpath="https://"+bucketName+"."+endpoint+"/"+objectName;

            // https://liuhongfei.oss-cn-beijing.aliyuncs.com/a1954baf-78ef-4dab-89f2-82652033ad29.jpg

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return "index";
    }
    @GetMapping("aaa")
    public String aaa(){
        return "192.168.157.37:8080";
    }
}
